<?php

namespace app\index\controller;

use app\common\controller\Frontend;
use app\common\model\Area;
use app\common\model\Share;
use app\common\model\Something;
use app\common\model\UserDeposit;
use app\common\model\UserMoneyLog;
use app\common\model\Wechat;
use think\Config;
use think\Cookie;
use think\Hook;
use think\Db;
use think\Session;
use think\Validate;
use EasyWeChat\Foundation\Application;

/**
 * 会员中心
 */
class User extends Frontend
{
    protected $layout = 'default';
    protected $noNeedLogin = ['getaboutus'];
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        parent::_initialize();
        $auth = $this->auth;

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }

        //监听注册登录注销的事件
        Hook::add('user_login_successed', function ($user) use ($auth) {
            $expire = input('post.keeplogin') ? 30 * 86400 : 0;
            Cookie::set('uid', $user->id, $expire);
            Cookie::set('token', $auth->getToken(), $expire);
        });
        Hook::add('user_register_successed', function ($user) use ($auth) {
            Cookie::set('uid', $user->id);
            Cookie::set('token', $auth->getToken());
        });
        Hook::add('user_delete_successed', function ($user) use ($auth) {
            Cookie::delete('uid');
            Cookie::delete('token');
        });
        Hook::add('user_logout_successed', function ($user) use ($auth) {
            Cookie::delete('uid');
            Cookie::delete('token');
        });
    }

    /**
     * 空的请求
     * @param $name
     * @return mixed
     */
    public function _empty($name)
    {
        $data = Hook::listen("user_request_empty", $name);
        foreach ($data as $index => $datum) {
            $this->view->assign($datum);
        }
        return $this->view->fetch('user/' . $name);
    }


    /**
     * 出价竞拍
     */
    public function bid(){
        $user=$this->auth->getUser();
        $user_id=$user->id;
        $data['good_id']=$this->request->post('good_id');
        $data['user_id']=$user_id;
        $data['order_sn']=randSole(3,32,1);
        $data['money']=$this->request->post('money');
        $total_money=$this->request->post('total_money');
        $data['createtime']=time();
        $wechat =new Wechat();
        $orderTem=new AuctionOrderTem();

        $data['price']=$total_money;
        $playorder['title']='竞价商品支付';
        $playorder['order_sn']= $data['order_sn'];
        $playorder['money']= $data['money'];

        $orderTem->add($data);
        $check = $wechat->WeixinPrePay($playorder, $user->openid);
        if ($check['status'] == 400) {
            $this->error($check['msg']);
        }
        $this->success('提交中...','', $check['data']);

    }



    /**
     * 会员中心
     */
    public function index()
    {
        $site=\think\Config::get('site');
        $introduction=$site['introduction'];

        if($this->request->isAjax()){
            $RequestName=$this->request->post('RequestName');
            $user=$this->auth->getUser();

            if($RequestName=='ajax'){
                $userData=$this->auth->getUser();
                $this->success('请求成功','',$userData->toArray());
            }
            if($RequestName=='payment'){
                $userUpdate=\app\common\model\User::get($user->id);
                $userUpdate->is_vip=1;
                $userUpdate->save();
                $this->success('vip开通中');
            }

            $wechat =new Wechat();
            $site=Config::get('site');
            $money=$site['vip_cost'];
            $order=array(
                'title'=>'vip开通时间'.time(),
                'order_sn'=>randSole(3,32,1),
                'money'=>$money
            );
            $userUpdate=\app\common\model\User::get($user->id);
            $userUpdate->order_sn=$order['order_sn'];
            $userUpdate->is_vip=2;
            $userUpdate->save();
            $check = $wechat->WeixinVipPay($order,$user->openid);
            if ($check['status'] == 400) {
                $this->error($check['msg']);
            }

            if ($check['status'] == 200) {
                $this->success('确认支付','',$check['data']);
            }


        }

        if(empty($introduction)){
            $content='';
        }else{
            $introduction = str_ireplace("/uploads",url('/','',true,true).'uploads',$introduction);//用"你好"替换字符串中的"hello"
            $content=$introduction;
        }
        $options=configNew();
        $app = new Application($options);

        $js = $app->js;
        $this->view->assign('js',$js);
        $this->view->assign('title','个人中心');
        $this->view->engine->layout('layout/default');
        $this->view->assign('vip_content',$content);
         $this->view->assign('vip_cost',$site['vip_cost']);
        return $this->view->fetch();
    }

    /**
     * 注册会员
     */
    public function register()
    {
        $url = $this->request->request('url');
        if ($this->auth->id) {
            $this->success(__('You\'ve logged in, do not login again'), $url ? $url : url('user/index'));
        }
        if ($this->request->isPost()) {
            $username = $this->request->post('username');
            $password = $this->request->post('password');
            $email = $this->request->post('email');
            $mobile = $this->request->post('mobile', '');
            $captcha = $this->request->post('captcha');
            $token = $this->request->post('__token__');
            $rule = [
                'username'  => 'require|length:3,30',
                'password'  => 'require|length:6,30',
                'email'     => 'require|email',
                'mobile'    => 'regex:/^1\d{10}$/',
                'captcha'   => 'require|captcha',
                '__token__' => 'token',
            ];

            $msg = [
                'username.require' => 'Username can not be empty',
                'username.length'  => 'Username must be 3 to 30 characters',
                'password.require' => 'Password can not be empty',
                'password.length'  => 'Password must be 6 to 30 characters',
                'captcha.require'  => 'Captcha can not be empty',
                'captcha.captcha'  => 'Captcha is incorrect',
                'email'            => 'Email is incorrect',
                'mobile'           => 'Mobile is incorrect',
            ];
            $data = [
                'username'  => $username,
                'password'  => $password,
                'email'     => $email,
                'mobile'    => $mobile,
                'captcha'   => $captcha,
                '__token__' => $token,
            ];
            $validate = new Validate($rule, $msg);
            $result = $validate->check($data);
            if (!$result) {
                $this->error(__($validate->getError()), null, ['token' => $this->request->token()]);
            }
            if ($this->auth->register($username, $password, $email, $mobile)) {
                $this->success(__('Sign up successful'), $url ? $url : url('user/index'));
            } else {
                $this->error($this->auth->getError(), null, ['token' => $this->request->token()]);
            }
        }
        //判断来源
        $referer = $this->request->server('HTTP_REFERER');
        if (!$url && (strtolower(parse_url($referer, PHP_URL_HOST)) == strtolower($this->request->host()))
            && !preg_match("/(user\/login|user\/register)/i", $referer)) {
            $url = $referer;
        }
        $this->view->assign('url', $url);
        $this->view->assign('title', __('Register'));
        return $this->view->fetch();
    }

    /**
     * 会员登录
     */
    public function login()
    {
        $url = $this->request->request('url');
        if ($this->auth->id) {
            $this->success(__('You\'ve logged in, do not login again'), $url ? $url : url('user/index'));
        }
        if ($this->request->isPost()) {
            $account = $this->request->post('account');
            $password = $this->request->post('password');
            $keeplogin = (int)$this->request->post('keeplogin');
            $token = $this->request->post('__token__');
            $rule = [
                'account'   => 'require|length:3,50',
                'password'  => 'require|length:6,30',
                '__token__' => 'token',
            ];

            $msg = [
                'account.require'  => 'Account can not be empty',
                'account.length'   => 'Account must be 3 to 50 characters',
                'password.require' => 'Password can not be empty',
                'password.length'  => 'Password must be 6 to 30 characters',
            ];
            $data = [
                'account'   => $account,
                'password'  => $password,
                '__token__' => $token,
            ];
            $validate = new Validate($rule, $msg);
            $result = $validate->check($data);
            if (!$result) {
                $this->error(__($validate->getError()), null, ['token' => $this->request->token()]);
                return false;
            }
            if ($this->auth->login($account, $password)) {
                $this->success(__('Logged in successful'), $url ? $url : url('user/index'));
            } else {
                $this->error($this->auth->getError(), null, ['token' => $this->request->token()]);
            }
        }
        //判断来源
        $referer = $this->request->server('HTTP_REFERER');
        if (!$url && (strtolower(parse_url($referer, PHP_URL_HOST)) == strtolower($this->request->host()))
            && !preg_match("/(user\/login|user\/register)/i", $referer)) {
            $url = $referer;
        }
        $this->view->assign('url', $url);
        $this->view->assign('title', __('Login'));
        return $this->view->fetch();
    }

    /**
     * 注销登录
     */
    public function logout()
    {
        //注销本站
        $this->auth->logout();
        $this->success(__('Logout successful'), url('user/index'));
    }

    /**
     * 个人信息
     */
    public function profile()
    {
        $this->view->assign('title', __('Profile'));
        return $this->view->fetch();
    }

    /**
     * 修改密码
     */
    public function changepwd()
    {
        if ($this->request->isPost()) {
            $oldpassword = $this->request->post("oldpassword");
            $newpassword = $this->request->post("newpassword");
            $renewpassword = $this->request->post("renewpassword");
            $token = $this->request->post('__token__');
            $rule = [
                'oldpassword'   => 'require|length:6,30',
                'newpassword'   => 'require|length:6,30',
                'renewpassword' => 'require|length:6,30|confirm:newpassword',
                '__token__'     => 'token',
            ];

            $msg = [
            ];
            $data = [
                'oldpassword'   => $oldpassword,
                'newpassword'   => $newpassword,
                'renewpassword' => $renewpassword,
                '__token__'     => $token,
            ];
            $field = [
                'oldpassword'   => __('Old password'),
                'newpassword'   => __('New password'),
                'renewpassword' => __('Renew password')
            ];
            $validate = new Validate($rule, $msg, $field);
            $result = $validate->check($data);
            if (!$result) {
                $this->error(__($validate->getError()), null, ['token' => $this->request->token()]);
                return false;
            }

            $ret = $this->auth->changepwd($newpassword, $oldpassword);
            if ($ret) {
                $this->success(__('Reset password successful'), url('user/login'));
            } else {
                $this->error($this->auth->getError(), null, ['token' => $this->request->token()]);
            }
        }
        $this->view->assign('title', __('Change password'));
        return $this->view->fetch();
    }

    /**
     * 找到人/物提交信息
     */
    public function eureka(){
        $somethingModel=new Something();

        if($this->request->isAjax()){
            $somethingModel=new Something();
            $wechat=new Wechat();
            $user=$this->auth->getUser();
            $id=$this->request->post('id');
            $data['eurekaContent']=$this->request->post('eurekaContent');
            if(empty($data['eurekaContent'])){
                $this->error('必须输入内容');
            }
            $data['eurekaimages']=input('post.eurekaimages/a');//$this->request->post('eurekaimages');
            if(count($data['eurekaimages'])==0){
                $this->error('至少上传一张图片');
            }
            $data['eurekaimages']=implode(',',$data['eurekaimages']);
            $data['status']=2;
            $data['updatetime']=time();
            $data['receiverUserId']=$user->id;

            $UpdateStatus=$somethingModel->InsertSome($data,$id);
            $somethingData=Something::get($id);
            if($UpdateStatus>0){
                $templateData['keyword1']=randSole(5,6);
                $templateData['keyword2']=$somethingData->content;
                $templateData['keyword4']=$user->nickname;
                $receiverUser=\app\common\model\User::get($somethingData['publisherUserId']);
                $templateData['keyword3']=$receiverUser->nickname;
                $templateData['remark']='请及时处理';

                try{
                    $tempStatus= $wechat
                        ->template('ra11Lhawrk3tG79AILUkzW1EjBH6FE-YV9zUfwimbMg',url('user/mypublish',
                            array('id'=>$id),true,true),$templateData,
                            $receiverUser->openid);
                }catch (\Exception $e){

                }

                $this->success('提交成功');
            }else{
                $this->error('提交失败请重新提交');
            }
        }

        $id=$this->request->param('id');
        $something=$somethingModel::get($id);
        if($something->status>=2){
            $this->success('正在进行确认中',url('index/detail',array('id'=>$id)));
        }


        $images=explode(',',$something['eurekaimages']);
        if(is_array($images)){
            $detailOne['eurekaimages']=$images;
        }else{
            $images=$something['eurekaimages'];
        }


        $this->view->assign('images',$images);
        $this->view->assign('id',$id);
        $this->view->assign('something',$something);
        $this->view->engine->layout('layout/newdefault');
       return $this->view->fetch();
    }

    /**
     * 失物招领并支付
     */
    public function claim(){
        $site=\think\Config::get('site');
        $somethingModel=new Something();
        $id=$this->request->param('id');
        $something=$somethingModel::get($id);
        if($this->request->isAjax()){
            $RequestName=$this->request->post('RequestName');
            $user=$this->auth->getUser();

            $id=$this->request->post('id');


            if(isset($RequestName)&&$RequestName=='ajax'){
                $this->success('请求成功','',$something);
            }

            if(!empty($something->receiverUserId)){
                $this->error('已有失物招领者,你不能失物招领者');
            }


            $data['eurekaContent']=$this->request->post('eurekaContent');
            if(empty( $data['eurekaContent'])){
                $this->error('必须输入内容');
            }
            $picturs= input('post.picturs/a');///$this->request->post('picturs');
            if(count($picturs)==0){
                $this->error('必须上传一张图片');
            }
            if(!empty($picturs)){
                $data['eurekaimages']=implode(',',$picturs);
            }else{
                $data['eurekaimages']='';
            }



            $data['updatetime']=time();
            $data['receiverUserId']=$user->id;

            $UpdateStatus=$somethingModel->InsertSome($data,$id);



            if($UpdateStatus>0){
                $user=$this->auth->getUser();
                $wechat =new Wechat();
                $order=array(
                    'title'=>cut_str($something['content'],10,'...'),
                    'order_sn'=>randSole(3,32,1),//$data['partner_trade_no'],
                    'money'=>$something['money']
                );

                $somethingAjax=$somethingModel::get($id);


                $somethingAjax->partner_trade_no=$order['order_sn'];
                $somethingAjax->save();

//                $templateData['keyword1']=randSole(5,6);
//                $templateData['keyword2']=$somethingAjax->content;
//                $templateData['keyword3']=$user->nickname;
//                $receiverUser=\app\common\model\User::get($somethingAjax['publisherUserId']);
//                $templateData['keyword4']=$receiverUser->nickname;
//                $templateData['remark']='请及时处理';

                $check=$wechat->WeixinPrePay($order, $user->openid);
                if ($check['status'] == 400) {
//                    try{
//                        $tempStatus= $wechat
//                            ->template('ra11Lhawrk3tG79AILUkzW1EjBH6FE-YV9zUfwimbMg',url('user/mypublish',
//                                array(),true,true),$templateData,
//                                $receiverUser->openid);
//                    }catch (\Exception $e){
//
//                    }

                    $this->error($check['msg']);

                }
//                try{
//                    $tempStatus= $wechat
//                        ->template('ra11Lhawrk3tG79AILUkzW1EjBH6FE-YV9zUfwimbMg',url('user/mypublish',
//                            array(),true,true),$templateData,
//                            $receiverUser->openid);
//                }catch (\Exception $e){
//
//                }

                $this->success('提交成功','', $check['data']);
            }else{
                $this->error('提交失败请重新提交');
            }


        }

        $imagesNew=explode(',',$something['images']);

        $images=explode(',',$something['eurekaimages']);
        if(is_array($images)){
            $detailOne['eurekaimages']=$images;
        }else{
            $images=$something['eurekaimages'];
        }


        //分享可获得报酬
        if($site['completed_revenue']>0){
            if($site['completed_revenue']>100){
                $money=($something['money']*(100/100))/100;
            }else{
                $money=($something['money']*($site['completed_revenue']/100))/100;
            }
        }else{
            $money=0;
        }



        $something['imagesNew']=$imagesNew;
        $this->view->assign('money',$money);
//        $this->view->assign('imagesNew',$imagesNew);
        $this->view->assign('images',$images);
        $this->view->assign('id',$id);
        $this->view->assign('something',$something);
        $options=configNew();
        $app = new Application($options);

        $js = $app->js;
        $this->view->assign('js',$js);
//        $this->view->assign('config',$js);

        $this->view->engine->layout('layout/newdefault');
        return $this->view->fetch();
    }



    /**
     * 发布
     */
    public function publish(){

        if($this->request->isAjax()){
            $user=$this->auth->getUser();
            $RequestName=$this->request->post('RequestName');



            $somethingModel=new Something();
            $content=$this->request->post('content');
            $id=$this->request->post('id');
            $contacts=$this->request->post('contacts');
            $images=input('post.images/a');
            $money=$this->request->post('money');
            $type=$this->request->post('type');
            $cycle=$this->request->post('cycle');
            $iphone=$this->request->post('iphone');
            $detailedaddress=$this->request->post('detailedaddress');
            $address=$this->request->post('address');
            $province=$this->request->post('province',0);
            $city=$this->request->post('city',0);
            $area=$this->request->post('area',0);
            $longitude=$this->request->post('longitude');
            $latitude=$this->request->post('latitude');
            if(isset($RequestName)&&$RequestName=='payment'){
                $id=$this->request->post('id');
                $something=Something::get($id);
                $something->status=1;
                $something->save();
                $this->success('支付成功','');
            }

            if(isset($RequestName)&&$RequestName=='ajax'){
                $site=\think\Config::get('site');
                if($type==2||$type==3){
                    $site_look=$site['something_look'];
                }elseif($type==1){
                    $site_look=$site['lost_look'];
                }
                $site_look = str_ireplace("/uploads",url('/','',true,true).'uploads',  $site_look);//用"你好"替换字符串中的"hello"
                $this->success('请求成功','',$site_look);
            }
            if(!is_numeric($iphone)){
                $this->error('手机号不正确');
            }

            if($money<0.01){
                $this->error('支付金额必须大于0.01');
            }

//            if($money>1000){
//                $this->error('金额不能大于1000');
//            }




            if($money<=0){
                $this->error('金额必须大于0');
            }
            if(!is_numeric($money)){
                $this->error('金额必须是数字');
            }

            if(!empty($city)){
                $cityArea=Area::get(['name'=>$city]);
                $city=$cityArea->id;
            }

            if(!empty($province)){
                $provinceArea=Area::get(['name'=>$province]);
                $province=$provinceArea->id;
            }

            if(!empty($area)){
                $areaArea=Area::get(['name'=>$area]);
                $area=$areaArea->id;
            }

            if(count($images)==0){
                $this->error('至少上传一张图片');
            }else {
                $images=implode(',',$images);
            }




            $rule = [
                'content'   => 'require',
                'images'   => 'require',
                'money' => 'require',
                'type' => 'require',
                'cycle' => 'require',
                'iphone' => 'require',
                'detailedaddress' => 'require',
                'address' => 'require',
                'city' => 'require',
                'province' => 'require',
                'contacts' => 'require',

            ];

            $msg = [
                'content.require'  => '发布内容不能为空',
                'images.require'  => '发布图片至少一张',
                'money.require'  => '不能为空',
                'type.require'  => '必须选择类型',
                'cycle.require'  => '必须选择发布周期',
                'contacts.require'  => '联系人不能为空',
                'iphone.require'  => '手机号不能为空',
                'detailedaddress.require'  => '丢失详细地址不能为空',
                'address.require'  => '详细地址不能为空',
                'province.require'  => '省不能为空',
                'city.require'  => '市不能为空',
            ];
            $data = [
                'content'   => $content,
                'images'   => $images,
                'money' =>$money,
                'type' => $type,
                'cycle' =>$cycle,
                'iphone' => $iphone,
                'detailedaddress' =>$detailedaddress,
                'contacts'=>$contacts,
                'address' => $address,
                'city' => $city,
                'area' => $area,
                'province' => $province,
            ];

            $validate = new Validate($rule, $msg);
            $result = $validate->check($data);
            if($result){
                $data['partner_trade_no']=str_random(32);
                $wechat =new Wechat();
                $order=array(
                    'title'=>cut_str($data['content'],10),
                    'order_sn'=>randSole(3,32,1),//$data['partner_trade_no'],
                    'money'=>$data['money']
                );
                if($type==2||$type==3){
                    $data['status']=0;
                }elseif ($type==1){
                    $data['status']=1;
                }

                $data['longitude']=$longitude;
                $data['createtime']=time();
                $data['latitude']=$latitude;
                $data['publisherUserId']=$user->id;
                if(!empty($id)){
                    $somethingModel->UpdateDelay($data,$id);
                    $status=$id;
                }else{
                    $status=$somethingModel->InsertData($data);
                }

                if($status){

                     if($type==2){
                         $templateData['type']='你发布找人';
                     }elseif ($type==3){
                         $templateData['type']='你发布找物';
                     }elseif ($type==1){
                         $templateData['type']='您发布失物招领';
                     }
                    $SomeThingNew_s=$somethingModel::get($status);
                    $templateData['content']=$SomeThingNew_s->content;

                    if($type==2||$type==3){
                        $SomeThingNew_s=$somethingModel::get($status);
                        $SomeThingNew_s->partner_trade_no=$order['order_sn'];
                        $SomeThingNew_s->save();
                        $check = $wechat->WeixinPrePay($order, $user->openid);
                        if ($check['status'] == 400) {
                            $templateData['price']=$order['money'].'未支付';
//                            $tempStatus= $wechat
//                            ->template(1,url('index/detail',
//                                array('id'=>$status)),$templateData,
//                                $user->openid);
                            $this->error($check['msg']);

                        }
                        $check['data']['id']=$status;
//                    $this->assign('jsonData', $check['data']);
//                        $tempStatus= $wechat
//                            ->template(1,url('index/detail',
//                                array('id'=>$status)),$templateData,
//                                $user->openid);
                        $this->success('提交成功','', $check['data']);
                    }else{
                        $check['data']['id']=$status;

                        $this->success('提交成功','', []);
                    }





                }else{
                    $this->error('提交失败,请重新提交');
                }
            }else{
                $this->error($validate->getError());
            }
        }






        $options=configNew();
        $app = new Application($options);

        $js = $app->js;
        $this->view->assign('js',$js);
//        $this->view->assign('config',$js);

        return $this->view->fetch();
    }

    public function payok(){

        echo '支付成功';
        $this->view->engine->layout('layout/newdefault');
        return $this->view->fetch();
    }


    /**
     * 收益记录
     */
    public function withdrawals(){
        $UserMoneyLogModel=new UserMoneyLog();
        if($this->request->isAjax()){
            $page=$this->request->post('page',1);
            $user=$this->auth->getUser();
            $user_id=$user->id;
            $genre=$this->request->post('genre',1);

            $data=$UserMoneyLogModel->getMyWithdrawals($user_id,$page,$genre);


            if(empty($data)){
                $this->error('暂无数据','',[]);
            }else{
                $this->success('请求成功','',$data);
            }
        }
        $this->view->engine->layout('layout/newdefault');
        return $this->view->fetch();
    }

    /**
     * 提现记录
     */

    public function postallog(){
        $user=$this->auth->getUser();
        if($this->request->isAjax()){
            $UserDepositModel=new UserDeposit();
            $page=$this->request->post('page',1);
            $user=$this->auth->getUser();
            $user_id=$user->id;//Cookie::get('uid');
            $data=$UserDepositModel->getDepositLog($user_id,$page);
            if(empty($data)){
                $this->error('暂无数据','',[]);
            }else{
                $this->success('请求成功','',$data);
            }
        }
        $this->view->assign('user',$user);
        $this->view->engine->layout('layout/newdefault');
        return $this->view->fetch();
    }
    /**
     * 提现
     */
    public function postal(){
        $user=$this->auth->getUser();
        if($this->request->isAjax()){
            $user=$this->auth->getUser();
            $RequestName=$this->request->post('RequestName');
            $site=Config::get('site');
            $lowsum=$site['lowsum'];
            if($RequestName=='ajax'){
                $this->success('请求成功','',$lowsum);
            }

            $user=$this->auth->getUser();
            $money=$this->request->post('money');

            if(empty($user->is_authentic)){
                $this->error('必须认证方可提现');
            }

            if(empty($money)){
                $this->error('提现余额必须输入');
            }

            $data['weChatCcount']=$this->request->post('weChatCcount');

            if(empty( $data['weChatCcount'])){
                $this->error('提现微信账号必须输入');
            }

            if($money>$user['money']){
                $this->error('提现金额不能大于可提现金额');
            }

            if($money<1){
                $this->error('提现金额不能小于1元');
            }



            if($money<$lowsum){
                $this->error('不能小于最低提现金额'.$lowsum);
            }


            $data['user_id']=$user->id;
            $data['remark']='提现';
            $data['openid']=$user->openid;
            $data['partner_trade_no']=str_random(32);
            $data['wechantNickname']=$user->nickname;
            $data['cash_fee']=round($money*($site['service_charge']/100),2);
            $data['money']= $money-$data['cash_fee'];
            $data['iphone']=$user->mobile;
            $data['status']=1;
            $data['createtime']=time();
            $userDepositModel=new UserDeposit();
            $status=$userDepositModel->save($data);
            if($status){
                $this->success('提交成功');
            }else{
                $this->success('提现失败,请重新提交');
            }

        }
        $this->view->assign('user',$user);
        $this->view->engine->layout('layout/newdefault');
        return $this->view->fetch();
    }

    /**
     * 认证
     */
    public function authentic(){
        if($this->request->isAjax()){
            $user=$this->auth->getUser();
            $data['mobile']=$this->request->post('mobile');
            $data['authentic_image']=$this->request->post('authentic_image');

            $code=$this->request->post('code');
            if(empty($data['mobile'])){
                $this->engine('手机号必须输入');
            }
            if(empty(  $data['authentic_image'])){
                $this->engine('手持身份证照必须上传');
            }
            if(empty($code)){
                $this->engine('验证码必须输入');
            }
            $ret = \app\common\library\Sms::check( $data['mobile'], $code, 'tixian');

            if (!$ret) {
                $this->error('验证码不正确，或已过期');
            }
            $userModel=new \app\common\model\User();
            $data['is_authentic']=2;
            $status=$userModel->setUserUpdate($data,$user->id);
            if($status){
                $this->success('提交成功');
            }else{
                $this->error('提交失败,请重新提交');
            }

        }
        $this->view->engine->layout('layout/newdefault');
        return $this->view->fetch();
    }


    /**
     * 我的发布
     */
    public function mypublish(){
        $site=Config::get('site');

        $service=$site['service'];
        if($this->request->isAjax()){
            $user=$this->auth->getUser();
            $someThingModel=new Something();
            $RequestName=$this->request->post('RequestName');
            $page=$this->request->post('page',1);
            switch ($RequestName){
                case 1:
                    //类型：1全部,2已完成
                    $type=$this->request->post('type');
                    if($type==2){
                        $where['something.status']=array('in',array(3,4,5,6,7));
                    }else{
                        $where['something.status']=array('in',array(0,1,2));
                    }
                    $where['publisherUserId']=array('eq',$user->id);
                    $data=$someThingModel->getList($where,$page);
                    if(!empty($data)){
                        foreach ($data as $key=>$val){
                            $data[$key]['chat_url']=url('index/messageroom',
                                array(
                                    'user_id'=>$user->id,
                                    'reply_user_id'=>$val['receiverUserId'],
                                    'something_id'=>$val['id'],
                                )
                            );
                            $data[$key]['uid']=$user->id;
                        }
                        $this->success('请求成功','',$data);
                    }else{
                        $this->error('暂无数据','',[]);
                    }
                    break;
                case 2:
                    $id=$this->request->post('id');
                    //cycle类型：1=30天,2永久
                    $data['cycle']=$this->request->post('cycle',1);
                    $data['status']=1;
                    $status=$someThingModel->UpdateDelay($data,$id);
                    if($status){
                        $this->success('延期成功');
                    }else{
                        $this->error('提交失败,重新点击延期');

                    }
                    break;
                case 3:
                    $id=$this->request->post('id');
                    $thingData=Something::get($id);
                    $thingData=$thingData->toArray();
                    $user=$this->auth->getUser();
                    //status：状态已完成进行金额算法
                    $data['status']=$this->request->post('status');
//                    if($thingData['type']!=1){
//                        $data['receiverUserId']=$user->id;
//                    }

                    $status=$someThingModel->UpdateDelay($data,$id);
                    if($status){
                        $UserMoneyLogModel=new UserMoneyLog();
                        $thingData=Something::get($id);
                        $this->success('已完成');
                    }else{
                        $this->error('失败');
                    }
                    break;
                case 4:
                    //更状态
                    $id=$this->request->post('id');
                    $id=(int)$id;
                    $data['status']=$this->request->post('status');
                    if($data['status']==1){
                        $wechat =new Wechat();
                        $data['receiverUserId']=0;
                        $data['status']=1;
                        $data['eurekaimages']='';
                        $data['eurekaContent']='';
                        $data['updatetime']=0;
                        $someThingData=Something::get($id);

                        $str=cut_str($someThingData->content,10,'...');
                        $receiverUser=\app\common\model\User::get($someThingData['receiverUserId']);
                        $publishUser=\app\common\model\User::get($someThingData['publisherUserId']);
                        $templateData['first']='您好，您申请的“'.$str.'”未通过。';
                        $templateData['keyword1']=$receiverUser->nickname;
                        $templateData['keyword2']=$someThingData->updatetime;
                        $templateData['keyword3']=date('Y-m-d H:i:s',time());
                        if($someThingData->type==1){
                            $somelogData['receiverName']=$receiverUser->nickname;
                            $somelogData['publishName']=$publishUser->nickname;
                            $somelogData['something_id']=$id;
                            $somelogData['partner_trade_no']=$someThingData->partner_trade_no;
//                            $somelogData['money']=$someThingData-money;
                            Db::name('somelog')->insert($somelogData);
                            $templateData['remark']='你支付的认领金额将会在2-5个工作日原路退回';
                        }else{
                            $templateData['remark']='请填写正确的有效信息，重新申请。';
                        }

                        try{
                            $tempStatus= $wechat
                                ->template('MIq0WPtv_SBQY7fqqv93jD1xeTjRaGfGhgJxusOCKYY',url('index/detail',
                                    array('id'=>$id),true,true),$templateData,
                                    $receiverUser->openid);
                        }catch (\Exception $e){

                        }

                    }
                    $status=$someThingModel->UpdateDelay($data,$id);
                    if($status){
                        $this->success('删除成功');
                    }else{
                        $this->error('请求失败,重新点确定');

                    }
                    break;
                //删除
                case 5:
                    $id=$this->request->post('id');

                    $where_del['id']=array('eq',$id);
                    $someThingModel->where($where_del)->delete();
                    $this->success('删除成功');
                    break;
                //支付
                case 6:
                    $id=$this->request->post('id');
                    $someThingOne=Something::get($id);
                    $order=array(
                        'title'=>$someThingOne->content,
                        'order_sn'=>randSole(3,32,1),//$data['partner_trade_no'],
                        'money'=>$someThingOne->money
                    );
                    $wechat =new Wechat();
                    $check = $wechat->WeixinPrePay($order, $user->openid);
                    if ($check['status'] == 400) {
                        $this->error($check['msg']);
                    }else{
                        $someThingOne->partner_trade_no=$order['order_sn'];
                        $someThingOne->status=1;
                        $someThingOne->save();
                        $check['data']['id']=$someThingOne->id;
                    }
                    $this->success('提交成功','', $check['data']);
                    break;
                default:
                    $this->error('暂无数据','',[]);
                    break;
            }
        }
        $options=configNew();
        $app = new Application($options);

        $js = $app->js;
        $this->view->assign('js',$js);
        $this->view->assign('service',$service);
        $this->view->engine->layout('layout/newdefault');
        return $this->view->fetch();
    }

    /**
     * 我参与的/我找到的
     */
    public function participate(){
        if($this->request->isAjax()){
            $site=\think\Config::get('site');
            $user=$this->auth->getUser();
            $someThingModel=new Something();
            $RequestName=$this->request->post('RequestName');
            switch ($RequestName){
                case 1:
                    $shreModel=new Share();
                    $page=$this->request->post('page');
                    $user_id=$user->id;
                    $data=$shreModel->getShareAll($user_id,$page);
                    if(!empty($data)){
                        $user=$this->auth->getUser();
                        foreach ($data as $key=>$val){

                            if($val['something']['type']==1){
                                if(!empty($site['completed_revenue'])&&$site['completed_revenue']>0){
                                    if($site['completed_revenue']>100){
                                        $site['completed_revenue']=100;
                                    }
                                    $data[$key]['partake']=$val['something']['money']*(1-$site['completed_revenue']/100);

                                }else{
                                    $data[$key]['partake']=0;
                                }

                            }elseif($val['something']['type']==2||$val['something']['type']==3){

                                if(!empty($site['share_profit'])&&$site['share_profit']>0){
                                    if($site['share_profit']>100){
                                        $site['share_profit']=100;
                                    }
                                    $data[$key]['partake']=$val['something']['money']*(1-$site['share_profit']/100);

                                }else{
                                    $data[$key]['partake']=0;
                                }

                            }
//                            $data[$key]['partake']=$val['something']['partake'];
                            $data[$key]['browse']=$val['something']['browse'];
                            $data[$key]['content']=$val['something']['content'];
                            $data[$key]['cycle']=$val['something']['cycle'];
                            $data[$key]['deadline']=$val['something']['deadline'];
                            $data[$key]['detailedaddress']=$val['something']['detailedaddress'];
                            $data[$key]['images']=$val['something']['images'];
                            $data[$key]['imageslist']=$val['something']['imageslist'];
                            $data[$key]['money']=$val['something']['money'];
                            if($val['something']['type']==1){
                                $data[$key]['label']='失物招领';
                                $data[$key]['q_name']='报酬';
                            }elseif ($val['something']['type']==2){
                                $data[$key]['q_name']='赏金';
                                $data[$key]['label']='找人';
                            }elseif ($val['something']['type']==3){
                                $data[$key]['label']='找物';
                                $data[$key]['q_name']='赏金';
                            }
//                            $data[$key]['label']=$val['something']['label'];
                            $data[$key]['publisherUserId']=$val['something']['publisherUserId'];
//                            $data[$key]['q_name']=$val['something']['q_name'];
                            $data[$key]['receiverUserId']=$val['something']['receiverUserId'];
                            $data[$key]['status']=$val['something']['status'];
                            $data[$key]['status_name']=$val['something']['status_name'];
                            $data[$key]['type']=$val['something']['type'];
                            $data[$key]['url']=$val['something']['url'];
                            $data[$key]['user']=\app\admin\model\User::get($val['something']['publisherUserId']);
                            $data[$key]['chat_url']=url('index/messageroom',
                                array(
//                            'chat_id'=>$val['id'],
                                    'user_id'=>$user->id,
                                    'reply_user_id'=>$val['something']['publisherUserId'],
                                    'something_id'=>$val['something']['id'],
                                )
                            );
                        }
                        $this->success('请求成功','',$data);
                    }else{
                        $this->error('暂无数据','',[]);
                    }
                    break;
                case 2:
                    $somethingModel=new Something();
                    $page=$this->request->post('page');
                    $user_id=$user->id;
//                    $where_1['publisherUserId']=array('eq',$user_id);
//                    $where_1['type']=array('in',array(2,3));
//                    $where_1['status']=array('in',array(3,4,5));

                    $where['receiverUserId']=array('eq',$user_id);
//                    $where['type']=array('in',array(1));
                    $where['something.status']=array('in',array(2,3,4,5));
//                    $data=array();
                    $data=$somethingModel->getList($where,$page);
//                    $data2=$somethingModel->getList($where_2,$page);
//                    if(!empty($data1)&&!empty($data2)){
//                        $data=array_merge($data1,$data2);
//                    }elseif (!empty($data1)){
//                        $data=$data1;
//                    }elseif (!empty($data2)){
//                        $data=$data2;
//                    }

                    if(empty($data)){
                        $this->error('暂不数据','',[]);
                    }else{
                        $user=$this->auth->getUser();
                        foreach ($data as $key=>$val){
                            $data[$key]['chat_url']=url('index/messageroom',
                                array(
//                            'chat_id'=>$val['id'],
                                    'user_id'=>$user->id,
                                    'reply_user_id'=>$val['publisherUserId'],
                                    'something_id'=>$val['id'],
                                )
                            );
                        }
                        $this->success('请求成功','',$data);
                    }

                    break;
                case 3:
                    $id=$this->request->post('id');
                    //status：状态已完成进行金额算法
//                    $data['status']=$this->request->post('status');
//                    $status=$someThingModel->UpdateDelay($data,$id);
//                    if($status){
//                        $UserMoneyLogModel=new UserMoneyLog();
//                        $thingData=Something::get($id);
////                        $UserMoneyLogModel->gold($thingData->type,$thingData->publisherUserId,$thingData->receiverUserId,$thingData->money,$id);
//                        $this->success('已完成');
//                    }else{
//                        $this->error('失败');
//                    }
                    break;
                default:
                    $this->error('暂无数据','',[]);
                    break;
            }


        }
        $options=configNew();
        $app = new Application($options);

        $js = $app->js;
        $this->view->assign('js',$js);
        $this->view->engine->layout('layout/newdefault');
        return $this->view->fetch();
    }

    /**
     * 关于我们接
     */
    public function getaboutus(){
            $site=\think\Config::get('site');
            $aboutus=$site['about'];
            if(empty($aboutus)){
                $content='';
            }else{
                $aboutus = str_ireplace("/uploads",url('/','',true,true).'uploads',$aboutus);//用"你好"替换字符串中的"hello"
                $content=$aboutus;
            }
        $this->view->assign('content',$content);
        $this->view->engine->layout('layout/newdefault');
        return $this->view->fetch();

    }

    /**
     * 开通vip支付
     */
    public function vip(){
        $pay_ok=$this->request->put('pay');
        if(isset($pay_ok)){

            $this->view->engine->layout('layout/newdefault');
            return $this->view->fetch('');
        }

        $user=$this->auth->getUser();
        $wechat =new Wechat();
        $site=Config::get('site');
        $money=$site['vip_cost'];
        $order=array(
            'title'=>'vip开通时间'.date(),
            'order_sn'=>randSole(3,32,1),
            'money'=>$money
        );

        $userUpdate=\app\common\model\User::get($user->id);
        $userUpdate->order_sn=$order['order_sn'];
        $userUpdate->save();

        $check = $wechat->WeixinVipPay($order,$user->openid);
        if ($check['status'] == 400) {
            $this->error($check['msg']);
        }

        $options=configNew();
        $app = new Application($options);

        $js = $app->js;
        $this->view->assign('js',$js);

        $this->view->assign('config',$check['data']);

        $this->view->engine->layout('layout/newdefault');
        return $this->view->fetch();
    }

    /**
     * 会员介绍
     */
    public function introduction(){
        $site=\think\Config::get('site');
        $aboutus=$site['introduction'];
        if(empty($aboutus)){
            $content='';
        }else{
            $aboutus = str_ireplace("/uploads",url('/','',true,true).'uploads',$aboutus);//用"你好"替换字符串中的"hello"
            $content=$aboutus;
        }
        $this->view->assign('content',$content);
        $this->view->engine->layout('layout/newdefault');
        return $this->view->fetch();
    }


}
